<template>
  <el-dialog :title="title" :width="width"
             :visible.sync="isShowVisible"
             center :close-on-click-modal="false"
             :before-close="() => this.close(false)">
    <el-card>
      <el-form label-width="105px" :model="maPackData" ref="maPackData" :rules="rules" v-loading="isLoading">
        <el-row>
          <el-col :span="6">
            <el-form-item label="编码:" prop="fnumber" >
                <el-input v-model="maPackData.fnumber" :disabled="isview"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="名称:" prop="fname" >
                <el-input v-model="maPackData.fname" :disabled="isview" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="数量:" prop="fqty" >
                <el-input-number v-model="maPackData.fqty" :disabled="isview"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计量类型:" prop="funittype" >
                 <tie-enum v-if="!isLoading" v-model="maPackData.funittype" :status="status" default="主计量"
                          className="cn.hxlc.tie.mdm.core.enums.MeasureTypeEnum" ></tie-enum>
              </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="产品编码:" prop="fmaterialid" >
                <inputSelect v-if="!isLoading" :f7Disable="isview" v-model="maPackData.fmaterialid" :loadShow="maPackData.fmaterialnumber" :f7Param="materialf7Param" title="产品列表" @onF7DaTaSelected="onF7MaterialSelected" ></inputSelect>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品名称:"  >
                <el-input v-model="maPackData.fmaterialname" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:" >
                  <el-input type="textarea" v-model="maPackData.fdescription" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">包材信息</el-divider>
        <el-row>
            <div style="margin-bottom:10px" v-if="!isview">
                <el-button type="primary"  plain size="small" @click="insertField(-1)" >新增</el-button>
                <el-button type="danger"   plain size="small" @click="$refs.xTable1.removeCheckboxRow()" >删除</el-button>
            </div>
        </el-row>
        <el-row>
            <vxe-table border
                show-overflow
                highlight-hover-row
                stripe
                resizable
                ref="xTable1"
                class="my_table_insert"
                max-height="300"
                :data="maPackData.entrys"
                :auto-resize="true"
                :edit-rules="entryRules"
                :edit-config="entryConfig">
                <vxe-table-column type="checkbox" width="60"></vxe-table-column>
                  <vxe-table-column field="fmaterialid" title="包材id" v-if="false"></vxe-table-column>
                  <vxe-table-column field="fmaterialnumber" title="包材编码" :edit-render="{type: 'default'}">
                    <template v-slot:edit="subscope">
                      <inputSelect v-model="subscope.row.fnumber" :loadShow="subscope.row.fnumber"  
                      :f7Param="entryMaterialF7Param" title="包材列表" @onF7DaTaSelected="onEntryMaterialSelectChanged"></inputSelect>
                    </template>
                    <template v-slot="{ row }">{{ row.fmaterialnumber }}</template>
                  </vxe-table-column>
                  <vxe-table-column field="fmaterialname" title="包材名称" ></vxe-table-column>
                  <vxe-table-column field="fmaterialmodel" title="包材规格" ></vxe-table-column>
                  <vxe-table-column field="funitid" title="计量单位"  :edit-render="{name: '$select', options : unitList}"></vxe-table-column>
                  <vxe-table-column field="fqty" title="包材数量" :edit-render="{name: 'input', attrs: {type: 'number'}}"></vxe-table-column>
                  <vxe-table-column field="fisminimum" title="最小包装" :edit-render="{name: '$select', options : yesOrNoList}"></vxe-table-column>
                  <vxe-table-column field="ftagtypeid" title="标签类型" :edit-render="{name: '$select', options : tagtypeList}"></vxe-table-column>
                  <vxe-table-column field="fdescription" title="备注" width="400" show-overflow=false :edit-render="{name: 'textarea'}"></vxe-table-column>
              </vxe-table>
        </el-row>
      </el-form>
    </el-card>
    <div slot="footer" class="dialog-footer" v-if="!isview">
      <el-button type="primary" @click="saveMaPackData">保存</el-button>
      <el-button @click="close(false)">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import UnitApi from '@/api/basedata/UnitApi'
  import OtherWebApi from '@/api/other/OtherWebApi'
  import MaPackApi from '@/api/material/MaPackApi'
  export default {
    name: 'maPack_addEdit',
    props:{
      width : {type : String , default : '80vw'},
      fid : {type : Number , },
      status : {type : String , },
    },
    data(){
      return{
        title:'新增物料包装',
        isShowVisible:true,
        isview : false,
        rules:{
          fqty:[{type: 'number',required: true, message: '请填写包装数量', tirgger: 'blur'}],
          fmaterialid:[{type: 'number',required: true, message: '请选择主材', tirgger: 'change'}],
        },
        entryRules: {
          fmaterialnumber: [{ required: true, message: '包材不能为空！' }],
          ftagtypeid: [{ required: true, message: '标签类型不能为空！' }],
          fqty: [{required: true, message: '包材数量不能为空！' }],
          funitid: [{required: true, message: '计量单位不能为空！' }],
        },
        entryConfig:{trigger: 'click', mode: 'cell'},
        yesOrNoList:[{value:false,label:"否"},{value:true,label:"是"}],
        materialf7Param : {
             selectId:'fid',
                    selectUrl:'/tie-demo/material/queryListPage',
                    selectTreeField:['fgroupid'],
                    selectTreeUrl:'/tie-demo/materialGroup/queryGroupTree',
                    selectShow:{spt:'',field:['fnumber']},
                    column:[
                            {lable:'物料编码',prop:'fnumber',isFilter:false,filterField:'xNumber'},
                            {lable:'物料简称',prop:'fsimplename',isFilter:false,filterField:'xId'},
                            {lable:'状态',prop:'fstatus',isFilter:false,filterField:'xDescription'},
                            {lable:'物料名称',prop:'fname',isFilter:false,filterField:'xBeizhu'},
                            {lable:'创建日期',prop:'fcreatetime',isFilter:false,filterField:'xDate'},
                            //{lable:'物料分类',prop:'fgroupid',isFilter:false,filterField:'fGroupId'},
                    ],
        },
        entryMaterialF7Param :{
            selectId:'fnumber',
            selectUrl:'/tie-mdm/material/queryListPage',
            selectTreeField:['fgroupid'],
            selectTreeUrl:'/tie-mdm/materialGroup/queryGroupTree',
            selectShow:{spt:'',field:['fnumber']},
            column:[{lable:'编号',prop:'fnumber',isFilter:true,filterField:'fnumber'},{lable:'名称',prop:'fname',isFilter:false,filterField:'fname'}
            ,{lable:'规格型号',prop:'fmodel',isFilter:false,filterField:'fmodel'}
            ,{lable:'简称',prop:'fsimplename',isFilter:true,filterField:'fsimplename'}
            ],
            defaultFilter:[{field:'fstatus',value:"USED"},{field:'fispackage',value:1}]
        },
        isLoading : false,
        maPackAPi : new MaPackApi(),
        otherWebApi : new OtherWebApi(),
        maPackData : {fqty : 1},
        tagtypeList : [],
        unitList : [],
        unitApi : new UnitApi()
      }
    },
    async created(){
      this.isLoading = true
      if(this.status == 'add'){

      }else{
          if(this.status == 'edit'){
              this.title = "编辑物料包装"
          }else if(this.status == 'view'){
              this.title = "查看物料包装";
              this.isview = true;
              this.rules = {};
              this.entryConfig = {};
              this.entryRules = {};
          }
          let maPackData = await this.maPackAPi.detail({fid:this.fid})
          this.maPackData = maPackData.data;
      }
      this.getTagtypeList();
      this.getUnitList();
      this.isLoading = false
    },
    methods:{
      getTagtypeList(){
        this.otherWebApi.getTagtypeList().then(res => {
          let tagtypeList = res.data;
          this.tagtypeList = [];
          for (var i=0;i < tagtypeList.length;i++) {
            this.tagtypeList.push({
                value: tagtypeList[i].fid,
                label: tagtypeList[i].fname,
            })
          }
        })
      },
      getUnitList(){
        this.unitApi.queryList().then(res => {
          let unitList = res.data;
          this.unitList = [];
          for (var i=0;i < unitList.length;i++) {
            this.unitList.push({
                value: unitList[i].fid,
                label: unitList[i].fname,
            })
          }
        })
      },
      onEntryMaterialSelectChanged(row){
        if(row!=null&&row!=undefined){
          this.$refs.xTable1.getActiveRecord().row.fmaterialid = row.fid;
          this.$refs.xTable1.getActiveRecord().row.fmaterialnumber = row.fnumber;
          this.$refs.xTable1.getActiveRecord().row.fmaterialname = row.fname;
          this.$refs.xTable1.getActiveRecord().row.fmaterialmodel = row.fmodel;
          this.$refs.xTable1.getActiveRecord().row.funitid = row.funitid;
        }else{
          this.$refs.xTable1.getActiveRecord().row.fmaterialid = null
          this.$refs.xTable1.getActiveRecord().row.fmaterialnumber = null
          this.$refs.xTable1.getActiveRecord().row.fmaterialname = null
          this.$refs.xTable1.getActiveRecord().row.fmaterialmodel = null
          this.$refs.xTable1.getActiveRecord().row.funitid = null
        }
      },
      async insertField(row){
        let { row: newRow } = await this.$refs.xTable1.insertAt({}, row)
        await this.$refs.xTable1.setActiveCell(newRow, 'fieldName')
      },
      onF7MaterialSelected(row){
        this.maPackData.fmaterialname = row.fname;
        this.maPackData.fmaterialmodel = row.fmodel;
      },
      async saveMaPackData(){
        const errMap = await this.$refs.xTable1.validate(true).catch(errMap => errMap)
        if (errMap) {
          return
        }
        this.$refs['maPackData'].validate((valid, object) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请耐心等待.....',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            let entrys = this.$refs.xTable1.getTableData().tableData;
            if(entrys.length == 0){
              this.$tie.showError('','分录不能为空！');
              return;
            }
           
            let maPackData = this.maPackData;
            maPackData.entrys = entrys;
            if(this.status == 'add'){
                this.maPackAPi.add(maPackData).then(res => {
                    loading.close()
                    this.$tie.showSuccess(res.message)
                    this.close(true)
                }).catch(e => {
                    loading.close()
                })  
            }else if(this.status == 'edit'){
                this.maPackAPi.update(maPackData).then(res => {
                    loading.close()
                    this.$tie.showSuccess(res.message)
                    this.close(true)
                }).catch(e => {
                    loading.close()
                })
            }
          } 
        })
      },
      close(isOk){
        this.$emit('close',isOk)
      }
    },
  }
</script>
<style lang="scss">
.vxe-select--panel {
  z-index: 3001 !important;
}

.col--actived{
  height: 125px !important;

  .vxe-cell{
    height: 90%;

    textarea{
      height: 100%;
    }
  }
}
</style>